import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;

/**
 * 嵌入式tomcat服务器
 *
 * @author ChangLiang
 * @date 2020/2/21
 */
public class EmbeddedTomcatServer {

    public static void main(String[] args) throws LifecycleException, ServletException {
        // 获取classes目录绝对路径
        String userDir = System.getProperty("user.dir");
        String classPath = userDir + File.separator + "target" + File.separator + "classes";
        System.out.println(classPath);

        Tomcat tomcat = new Tomcat();
        // set http port
        tomcat.setPort(9090);

        Host host = tomcat.getHost();
        host.setName("localhost");
        host.setAppBase("webapps");

        // set service
        Service service = tomcat.getService();

        // set connector
        Connector connector = new Connector();
        connector.setPort(9090);
        connector.setURIEncoding("UTF-8");
        connector.setProtocol("HTTP/1.1");
        service.addConnector(connector);



        String contextPath = "/";
        String webapp = userDir + File.separator + "src" + File.separator + "main" + File.separator + "webapp";

        // 设置webapp绝对路径到Context 作为其docBase
        Context context = tomcat.addWebapp(contextPath, webapp);
        if (context instanceof StandardContext) {
            StandardContext standardContext = (StandardContext) context;
            // 设置默认的web.xml文件到Context
            standardContext.setDefaultWebXml(classPath + File.separator + "conf" + File.separator + "web.xml");

            // 设置classpath 到 Context

            // 添加servlet到tomcat容器 并 设置好mapping
            Wrapper wrapper = tomcat.addServlet(contextPath, "BbsServlet", new BbsServlet());
            wrapper.addMapping("/bbs/findAll");

        }

        tomcat.start();
        // 强制tomcat server等待 避免main线程执行结束关闭
        tomcat.getServer().await();
    }
}
